package com.atwulidun.prototype03.shallowcopy;

public class ShallowCopy {
    public static void main(String[] args) {
        Sheep sheep = new Sheep("喜洋洋", 3, "白色");
        // 设置sheep中的引用类型成员变量
        sheep.setSheep(new Sheep("懒洋洋",1,"黑色"));
        // 拷贝sheep
        Sheep sheep1 = (Sheep) sheep.clone();
        Sheep sheep2 = (Sheep) sheep.clone();
        Sheep sheep3 = (Sheep) sheep.clone();
        // 输出克隆对象中引用成员变量的hashCode，发现都是一样的，这就是浅拷贝
        System.out.println(sheep.getSheep().hashCode());
        System.out.println(sheep1.getSheep().hashCode());
        System.out.println(sheep2.getSheep().hashCode());
        System.out.println(sheep3.getSheep().hashCode());
    }
}

class Sheep implements Cloneable {
    private String name;
    private int age;
    private String color;
    // 增加一个引用数据类型来测试浅拷贝
    private Sheep sheep;

    public Sheep(String name, int age, String color) {
        this.name = name;
        this.age = age;
        this.color = color;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public Sheep getSheep() {
        return sheep;
    }

    public void setSheep(Sheep sheep) {
        this.sheep = sheep;
    }

    @Override
    public String toString() {
        return "Sheep{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", color='" + color + '\'' +
                '}';
    }

    @Override
    protected Object clone() {
        Object object = null;
        try {
            object = super.clone();
        } catch (CloneNotSupportedException e) {
            System.out.println(e.getMessage());;
        }
        return object;
    }
}
